package game.tictactoe.ui;

import game.tictactoe.impl.GameInterface;
import game.tictactoe.impl.GameInterfaceImpl;
import game.tictactoe.pojo.AIPlayerImpl;
import game.tictactoe.pojo.Board;
import game.tictactoe.pojo.HumanPlayerImpl;
import game.tictactoe.pojo.Player;
import game.tictactoe.pojo.Seed;
import game.tictactoe.util.Utils;

public class UserInterfaceImpl implements UserInterface
{
	public GameInterface gameInterface = GameInterfaceImpl.getGameInterfaceImpl();
	public Player humanPlayer = new HumanPlayerImpl(Seed.CROSS);
	public Player aiPlayer = new AIPlayerImpl(Seed.ZERO);
	public Board board;

	public void setUpTheGame()
	{
		gameInterface.setBoard(3, 3);
		board = gameInterface.getBoard();
		gameInterface.setUpPlayers(humanPlayer, aiPlayer);
	}

	public void playTheGame()
	{
		System.out.println("Welcome to Tic-Tac-Toe."); 
		System.out.println("Please make your move selection by entering a number 1-9 corresponding to the movement key on the right.");
		System.out.println("Board:  Movement Key:\n| |  	1|2|3\n| |  	4|5|6\n| |  	7|8|9");
		int humanInput = -2;
		int aiInput = -2;
		int gameStatus = -2;
		while (gameStatus == -2)
		{
			board = gameInterface.getBoard();
			humanInput = humanPlayer.getNextMove(board);
			boolean isValidMove = gameInterface.processMove(humanInput,humanPlayer.getMySeed());
			gameStatus = gameInterface.getGameStatus();
			if(isValidMove)
			{
				if (gameStatus == -2)
				{
					board = gameInterface.getBoard();
					aiInput = aiPlayer.getNextMove(board);
					isValidMove = gameInterface.processMove(aiInput, aiPlayer.getMySeed());	
					assert isValidMove : aiInput;
					gameStatus = gameInterface.getGameStatus();
					if(gameStatus == -2)
					{
						System.out.println(Utils.constructMessage(humanInput, aiInput, gameStatus));
						System.out.println(board.toString());
					}
				}
			}
			else
			{
				System.out.println("Invalid move. Please choose number from current board configuration that is empty: ");
				System.out.println(board.toString());
			}
		}
		if (gameStatus != -2)
		{
			System.out.println(Utils.constructMessage(humanInput, aiInput, gameStatus));
			System.out.println(board.toString());
		}
	}

	public static void main(String args[])
	{
		UserInterfaceImpl userInterface = new UserInterfaceImpl();
		userInterface.setUpTheGame();
		userInterface.playTheGame();
	}
}
